
const router = require('express').Router();
const userService = require('../../service/user/index');
const newService = require('../../service/news/news');
const fastStaticsService = require('../../service/news/statistics');
const joiValidator = require('../../utils/joi');
const Joi = require('joi');
const _ = require('lodash');

/**
 * 查询用户的收藏列表
 */
router.post('/collect/list', joiValidator({
    uid: Joi.required(),
    perPage: Joi.number().integer().min(3).max(20),
    page: Joi.number().integer().min(1)
}), (req, res, next)=> {

    let uid = req.body.uid;
    let page = req.body.page || 1;
    let perPage = req.body.perPage || 10;
    let fastInfo = [], fastStatics = {};

    //  获取用户的收藏列表
    userService.collectList({uid})
        .then((data)=> {
            let collectInfo = data.collect || [];   //注意这里的快讯因为是数组，所以默认顺序从后到前，这样就是按收藏时间排序
            let _ids = collectInfo
                .map((item)=> item._id) //提取出所有的快讯Id
                .sort((item)=> 1)       //按收藏顺序进行排序
                .slice((page - 1) * perPage, page * perPage);                //分页截取出需要的Id
            //  查询快讯详情

            return newService.getAllFastInfo({where: {_id: {$in: _ids}}, fields: '-__v -readNum'}, {
                lean: true, sort: {releaseDate: -1}
            })
        })
        .then((fast)=> {
            fastInfo = fast;
            let _ids = fast.map(item => item._id);
            if (!_ids || _ids.length === 0) {
                return Promise.resolve()
            }
            //  浏览过的就算读过了，次数加上
            return fastStaticsService.updateAndSaveFastStatics({_ids: _ids});
            // console.log(data)
        })
        .then((resp)=> {
            fastStatics = resp;
            //fixme 这一步超级蠢， 给改掉,用户名称这种东西 就应该冗余存！
            let authorIds = _.map(fastInfo, (item)=> {
                if (item.author.length > 3) {
                    return item.author;
                }
            });
            //获取发表快讯的作者名称
            return newService.getFastAuthor(authorIds)
        })
        .then((data)=> {
            let i;
            for (i = 0; i < fastInfo.length; i++) {
                let single = fastInfo[i];
                if (fastStatics[single._id]) {
                    fastInfo[i].viewCount = fastStatics[single._id].viewCount || 0;    //阅读次数
                    fastInfo[i].topCount = fastStatics[single._id].realTopCount || 0;      //点赞次数
                    fastInfo[i].collectCount = fastStatics[single._id].realCollectCount || 0;
                    fastInfo[i].playCount = fastStatics[single._id].playCount || 0;    //我来播次数
                } else {
                    fastInfo[i].viewCount = 1;
                    fastInfo[i].topCount = 0;
                    fastInfo[i].collectCount = 0;
                    fastInfo[i].playCount = 0;
                }
                //  添加名字
                fastInfo[i].author = data[single.author] && data[single.author].userName
                    || (fastInfo[i].author || '')
            }
            res.success(fastInfo)
        })
        .catch((err)=> {
            next(err)
        })
});

/**
 * 用户点击收藏，点赞，我来播，分享，详情展开接口
 */
router.post('/act', joiValidator({
    uid: Joi.required(),    //用户Id
    fastId: Joi.required(), //快讯Id
    handle: Joi.any().valid(['true', 'false']).required(),  //操作取消还是加入
    type: Joi.any().valid(['collect', 'vote', 'share', 'play', 'view']).required(),  //操作点赞还是收藏
}),(req, res, next)=> {

    let uid = req.body.uid, //用户Id
        fastId = req.body.fastId,   //快讯Id
        type,
        updateField,
        update = {},
        handle = false; //操作，默认取消

    if (req.body.handle === 'true') {
        handle = true
    }
    if (req.body.type === 'collect') {
        type = 'collect';
    }
    if (req.body.type === 'vote') {
        type = 'vote';
    }
    if (handle) {
        if (type === 'collect') {
            update = {$addToSet: {collect: {_id: fastId, timestamp: new Date().getTime()}}};   //  收藏快讯
            updateField = 'collectCount'
        }
        if (type === 'vote') {
            update = {$addToSet: {vote: {_id: fastId, timestamp: new Date().getTime()}}};      //点赞快讯
            updateField = 'topCount'
        }
    } else {
        if (type === 'collect') {
            update = {$pull: {collect: {_id: fastId}}};   //取消收藏快讯
            updateField = 'delCollectCount'
        }
        if (type === 'vote') {
            update = {$pull: {vote: {_id: fastId}}};  //取消点赞
            updateField = 'delTopCount'
        }
    }
    //  分享
    if (type === 'share') {
        type = 'shareCount';
    }
    //  我来播
    if (type === 'play') {
        type = 'playCount';
    }
    //  点击展开查看快讯
    if (type === 'view') {
        type = 'realViewCount'
    }

    return Promise.resolve()
        .then(()=> {
            //  分享和我来播就直接跳过
            if (type !== 'shareCount' && type !== 'playCount' && type !== 'realViewCount') {
                return userService.actFast({uid, fastId, update, updateField})
            }
        })
        .then(()=> {
            return fastStaticsService.updateFastStatics({_ids: fastId}, updateField)
        })
        .then(()=> {
            res.success()
        })
        .catch((err)=> {
            next(err)
        })
});

module.exports = router;